package com.plantuml.server.controller;

import com.plantuml.server.service.PlantUmlService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;

@RestController
@RequestMapping("/diagrams")
@CrossOrigin(origins = "*", allowCredentials = "false")
public class PlantUmlController {

    @Autowired
    private PlantUmlService plantUmlService;

    /**
     * 请求体类
     */
    public static class UmlCodeRequest {
        private String umlCode;

        public String getUmlCode() {
            return umlCode;
        }

        public void setUmlCode(String umlCode) {
            this.umlCode = umlCode;
        }
    }

    /**
     * 生成PlantUML图片（支持JSON请求体）
     * @param request 包含umlCode的JSON请求体
     * @return 图片字节数组
     */
    @PostMapping("/image")
    public ResponseEntity<byte[]> generateImage(@RequestBody UmlCodeRequest request) {
        try {
            if (request == null || request.getUmlCode() == null || request.getUmlCode().trim().isEmpty()) {
                System.out.println("Invalid request: request or umlCode is null/empty");
                return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
            }
            
            String umlCode = request.getUmlCode();
            System.out.println("Received PlantUML code: " + umlCode);
            
            byte[] imageBytes = plantUmlService.generateImage(umlCode);
            
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.IMAGE_PNG);
            headers.setContentLength(imageBytes.length);
            
            System.out.println("Generated image size: " + imageBytes.length + " bytes");
            
            return new ResponseEntity<>(imageBytes, headers, HttpStatus.OK);
        } catch (Exception e) {
            System.err.println("Error generating image: " + e.getMessage());
            e.printStackTrace();
            return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    /**
     * 生成PlantUML图片（兼容旧版本，支持纯文本请求体）
     * @param umlCode PlantUML代码（纯文本）
     * @return 图片字节数组
     */
    @PostMapping(value = "/image/text", consumes = MediaType.TEXT_PLAIN_VALUE)
    public ResponseEntity<byte[]> generateImageFromText(@RequestBody String umlCode) {
        try {
            System.out.println("Received PlantUML code (text): " + umlCode);
            
            if (umlCode == null || umlCode.trim().isEmpty()) {
                return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
            }
            
            byte[] imageBytes = plantUmlService.generateImage(umlCode);
            
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.IMAGE_PNG);
            headers.setContentLength(imageBytes.length);
            
            System.out.println("Generated image size: " + imageBytes.length + " bytes");
            
            return new ResponseEntity<>(imageBytes, headers, HttpStatus.OK);
        } catch (Exception e) {
            System.err.println("Error generating image: " + e.getMessage());
            e.printStackTrace();
            return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    /**
     * 生成PlantUML图片（GET方式，支持URL编码）
     * @param encoded PlantUML代码（URL编码）
     * @return 图片字节数组
     */
    @GetMapping("/image/{encoded}")
    public ResponseEntity<byte[]> generateImageFromUrl(@PathVariable String encoded) {
        try {
            byte[] imageBytes = plantUmlService.generateImageFromEncoded(encoded);
            
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.IMAGE_PNG);
            headers.setContentLength(imageBytes.length);
            
            return new ResponseEntity<>(imageBytes, headers, HttpStatus.OK);
        } catch (Exception e) {
            System.err.println("Error generating image from encoded: " + e.getMessage());
            e.printStackTrace();
            return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    /**
     * 健康检查接口
     * @return 服务状态
     */
    @GetMapping("/health")
    public ResponseEntity<String> health() {
        return ResponseEntity.ok("PlantUML Server is running");
    }
} 